package com.yupi.mybi.manager;

import com.yupi.mybi.common.ErrorCode;
import com.yupi.mybi.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedisLimiterManager {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 限流操作
     * @param key 根据key区分不同的限流器，比如不同的用户id
     */
    public void doRateLimiter(String key) {
        //获取一个限流器，每秒最多访问两次
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL,2,1, RateIntervalUnit.SECONDS);

        //每当一个操作过来，请求一个令牌
        boolean canOp = rateLimiter.tryAcquire(1);
        if(!canOp){
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }

    }


}
